/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.acceptancecheck.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.dto.ac.AcSearchDTO;
import com.fuyao.cloud.asset.entity.ac.AssetAc;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.acceptancecheck.service.AssetAcService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 验收管理
 *
 * @author liyue
 * @date 2021-12-03 09:41:17
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fyassetac")
@Api(value = "fyassetac", tags = "验收管理管理")
public class AssetAcController implements FlowableController {

    private final AssetAcService fyAssetAcService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param searchDTO 验收管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_view')")
    public R getFyAssetAcPage(Page page, AcSearchDTO searchDTO) {
        return R.ok(fyAssetAcService.page(page, SpliceQueryWrapper.spliceSearchCondition(searchDTO), searchDTO));
    }

    @ApiOperation(value = "分页查询带明细信息", notes = "分页查询带明细信息")
    @GetMapping("/getAcPage")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_view')")
    public R getAcPage(Page page, AssetAc fyAssetAc) {
        return R.ok(fyAssetAcService.getAcPage(page, Wrappers.query(fyAssetAc)));
    }

    /**
     * 通过id查询验收管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_view')")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(fyAssetAcService.getById(id));
    }

    /**
     * 新增验收管理
     *
     * @param fyAssetAc 验收管理
     * @return R
     */
    @ApiOperation(value = "新增验收管理", notes = "新增验收管理")
    @SysLog("新增验收管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_add')")
    public R save(@RequestBody AssetAc fyAssetAc) {
        fyAssetAcService.save(fyAssetAc);
        return R.ok(fyAssetAc);
    }

    /**
     * 修改验收管理
     *
     * @param fyAssetAc 验收管理
     * @return R
     */
    @ApiOperation(value = "修改验收管理", notes = "修改验收管理")
    @SysLog("修改验收管理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_edit')")
    public R updateById(@RequestBody AssetAc fyAssetAc) {
        return R.ok(fyAssetAcService.updateById(fyAssetAc));
    }

    /**
     * 通过id删除验收管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除验收管理", notes = "通过id删除验收管理")
    @SysLog("通过id删除验收管理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_del')")
    public R removeById(@PathVariable Long id) {
        return R.ok(fyAssetAcService.removeById(id));
    }


    /**
     * 导出excel 表格
     *
     * @param searchDTO 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_export')")
    public List export(AcSearchDTO searchDTO) {
        return fyAssetAcService.listAssetAc(SpliceQueryWrapper.spliceSearchCondition(searchDTO));
    }


    @GetMapping("/create")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_add')")
    public R create() {
        return R.ok(this.fyAssetAcService.create());
    }

    @GetMapping("/edit/{id}")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_edit')")
    public R edit(@PathVariable("id") Long id) {
        return R.ok(this.fyAssetAcService.edit(id));
    }

    @ApiOperation(value = "批量删除验收信息", notes = "批量删除验收信息")
    @SysLog("批量删除验收信息")
    @DeleteMapping("/batchDelete")
    @PreAuthorize("@pms.hasPermission('acceptancecheck_fyassetac_del')")
    public R batchDelete(@RequestBody List<Long> ids) {
        return fyAssetAcService.batchDelete(ids);
    }

    @ApiOperation(value = "上架入库单", notes = "上架入库单")
    @PostMapping(value = "/inorderByAC/{id}", produces = "application/json")
    public R inorderByAC(HttpServletRequest request, @PathVariable("id") Long id) {
        AssetAc assetAc = this.fyAssetAcService.getById(id);
        Assert.isTrue(ObjectUtil.isNotEmpty(assetAc), String.format("未找到验收单：%s",id));

        if(!AssetStatusEnum.APPROVE.getCode().equals(assetAc.getStatus())){
            R.failed("设备验收单尚未结束，不能进行入库上架");
        }
        return this.fyAssetAcService.createNinorder(assetAc);
    }

    @ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
    @PostMapping(value = "/draftEndCallback", produces = "application/json")
    @Override
    public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            AssetAc assetAc = this.fyAssetAcService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(assetAc), String.format("未找到对应的业务数据：%s", id));
            assetAc.setStatus(AssetStatusEnum.PROCESSING.getCode());
            this.fyAssetAcService.updateById(assetAc);
            return R.ok(assetAc, "修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
    }

    @ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
    @PostMapping(value = "/returnCallback", produces = "application/json")
    @Override
    public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            AssetAc assetAc = this.fyAssetAcService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(assetAc), String.format("未找到对应的业务数据：%s", id));
            assetAc.setStatus(AssetStatusEnum.DRAFT.getCode());
            this.fyAssetAcService.updateById(assetAc);
            return R.ok(assetAc,"修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
    }

    @ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
    @PostMapping(value = "/callback", produces = "application/json")
    @Override
    public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            AssetAc assetAc = this.fyAssetAcService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(assetAc), String.format("未找到对应的业务数据：%s", id));
            String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.APPROVE.getCode();
            assetAc.setStatus(status);
            this.fyAssetAcService.updateById(assetAc);
            return R.ok(assetAc, "修改状态成功");
        }
        return R.failed("未找到对应的业务数据");
    }

}
